package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    // @Scheduled(cron = "0 0/1 * * * ?")
    // @Scheduled(cron = "0/5 * * * * ?")
    public void proceedTimeOutOrder(){
        log.info("处理超时订单"+ LocalDateTime.now());
        //查询出超时的订单
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        // select * from orders where status=? and order_time < ?
        List<Orders> timeoutOrderList = ordersMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,localDateTime);

        //修超时订单状态为取消
        if(timeoutOrderList!=null && timeoutOrderList.size()>0){
            for (Orders orders : timeoutOrderList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("订单超时");
                orders.setCancelTime(LocalDateTime.now());

                ordersMapper.update(orders);
            }
        }

    }

    // @Scheduled(cron = "0 0 1 * * ?")
    // @Scheduled(cron = "0/5 * * * * ?")
    public void proceedDeliveryOrder(){
        log.info("处理派送中订单"+ LocalDateTime.now());
        //查询出派送中的订单
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        // select * from orders where status=? and order_time < ?
        List<Orders> deliveryOrderList = ordersMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,localDateTime);

        //修超时订单状态为完成
        if(deliveryOrderList!=null && deliveryOrderList.size()>0){
            for (Orders orders : deliveryOrderList) {
                orders.setStatus(Orders.COMPLETED);
                orders.setDeliveryTime(LocalDateTime.now());
                ordersMapper.update(orders);
            }
        }


    }
}
